package com.xoa.service.HSTmeeting;

import com.xoa.dao.HSTmeeting.HstMeetingMapper;
import com.xoa.dao.HSTmeeting.HstRoomMapper;
import com.xoa.dao.budget.BudgetLogMapper;
import com.xoa.dao.common.SysCodeMapper;
import com.xoa.dao.users.UsersMapper;
import com.xoa.model.HSTmeeting.HstMeetingWithBLOBs;
import com.xoa.model.HSTmeeting.HstRoomWithBLOBs;
import com.xoa.model.common.SysCode;
import com.xoa.model.enclosure.Attachment;
import com.xoa.model.sms.SmsBody;
import com.xoa.model.users.Users;
import com.xoa.service.sms.SmsService;
import com.xoa.service.smsDelivery.Sms2PrivService;
import com.xoa.util.CookiesUtil;
import com.xoa.util.DateFormat;
import com.xoa.util.GetAttachmentListUtil;
import com.xoa.util.ToJson;
import com.xoa.util.common.StringUtils;
import com.xoa.util.common.session.SessionUtils;
import com.xoa.util.dataSource.ContextHolder;
import com.xoa.util.page.PageParams;
import org.apache.commons.collections4.map.HashedMap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class HSTmeetingService {
    @Autowired
    private HstRoomMapper hstRoomMapper;

    @Autowired
    private HstMeetingMapper hstMeetingMapper;

    @Resource
    private UsersMapper usersMapper;

    @Resource
    ThreadPoolTaskExecutor threadPoolTaskExecutor;

    @Resource
    private SysCodeMapper sysCodeMapper;

    @Resource
    private SmsService smsService;

    @Resource
    private Sms2PrivService sms2PrivService;

    @Autowired
    private BudgetLogMapper budgetLogMapper;



    public ToJson<HstMeetingWithBLOBs> insertMeeting(HstMeetingWithBLOBs hstMeetingWithBLOBs, HttpServletRequest request){
        ToJson<HstMeetingWithBLOBs> json = new ToJson<HstMeetingWithBLOBs>(1, "error");
        Cookie redisSessionId = CookiesUtil.getCookieByName(request,"redisSessionId");
        Users user = SessionUtils.getSessionInfo(request.getSession(),Users.class,new Users(),redisSessionId);
        Map<String,Object> map=new HashedMap();
        map.put("meetRoomId",hstMeetingWithBLOBs.getRoomId());
        //int useRommTotalCount=hstMeetingWithBLOBs.selCountRoomNoConflict(map);//使用要申请的会议室的会议总数
        map.put("startTime",hstMeetingWithBLOBs.getStartTime());
        map.put("endTime",hstMeetingWithBLOBs.getEndTime());
     //   int useRommNoConflictCount=meetingMapper.selCountRoomNoConflict(map);//使用要申请会议室和已申请会议室不冲突的数量
        map.put("roomId",hstMeetingWithBLOBs.getRoomId());
        int nums = hstMeetingMapper.getHstMettingByTime(map);
        if (nums>=1) {
            json.setMsg("会议室已被占用,请重新修改时间");
            json.setFlag(1);
            return json;
        }
        try {
            hstMeetingWithBLOBs.setUserId(user.getUserId());//申请人
            hstMeetingWithBLOBs.setProposerTime(new Date());//申请时间
            int i = hstMeetingMapper.insertSelective(hstMeetingWithBLOBs);
            if ("1".equals(hstMeetingWithBLOBs.getSmsRemind())){//1 发送事务提醒
                addHstAffairs1(hstMeetingWithBLOBs,request);
            }
            if ("1".equals(hstMeetingWithBLOBs.getSmsRemind2())){//1 发送短信提醒
                addMessage(hstMeetingWithBLOBs,request,user.getUid());
            }
            json.setMsg("ok");
            json.setFlag(0);
        }catch(Exception e){
            json.setMsg(e.getMessage());
        }
        return json;
    }

    public ToJson<HstMeetingWithBLOBs> judgeMeeting(HstMeetingWithBLOBs hstMeetingWithBLOBs, HttpServletRequest request) {
        ToJson<HstMeetingWithBLOBs> json = new ToJson<HstMeetingWithBLOBs>(1, "error");
        //Cookie redisSessionId = CookiesUtil.getCookieByName(request,"redisSessionId");
        //Users user = SessionUtils.getSessionInfo(request.getSession(),Users.class,new Users(),redisSessionId);
        Map<String,Object> map=new HashedMap();
        map.put("meetRoomId",hstMeetingWithBLOBs.getRoomId());
        //int useRommTotalCount=hstMeetingWithBLOBs.selCountRoomNoConflict(map);//使用要申请的会议室的会议总数
        map.put("startTime",hstMeetingWithBLOBs.getStartTime());
        map.put("endTime",hstMeetingWithBLOBs.getEndTime());
        //   int useRommNoConflictCount=meetingMapper.selCountRoomNoConflict(map);//使用要申请会议室和已申请会议室不冲突的数量
        map.put("roomId",hstMeetingWithBLOBs.getRoomId());
        int nums = hstMeetingMapper.getHstMettingByTime(map);
        if (nums>=1) {
            json.setMsg("会议室已被占用,请重新修改时间");
            json.setFlag(1);
            json.setCode("1");
            return json;
        }
        json.setMsg("会议室可以使用");
        json.setFlag(0);
        json.setCode("0");
        return json;
    }

    private void addMessage(HstMeetingWithBLOBs hstMeetingWithBLOBs, HttpServletRequest request, Integer uid) {
        String content = "请审批会议，会议名称："+hstMeetingWithBLOBs.getMeetName();
        StringBuffer buffer2 = new StringBuffer();
        buffer2.append(content);
        sms2PrivService.smsSenders(buffer2,Integer.toString(uid));
    }
    private void addMessage1(HstMeetingWithBLOBs hstMeetingWithBLOBs, HttpServletRequest request, String userids) {//

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String date = sdf.format(hstMeetingWithBLOBs.getStartTime());
        String content = "请参加会议，会议名称："+hstMeetingWithBLOBs.getMeetName()+",会议开始时间"+date+"注意时间，请不要是迟到。";
        StringBuffer buffer2 = new StringBuffer();
        buffer2.append(content);
        String[] split = hstMeetingWithBLOBs.getUserIds().split(",");
        List<Users> usersByUids = usersMapper.getUsersByUserIds(split);
        StringBuffer sb = new StringBuffer();
        for (Users u : usersByUids) {
            sb.append(u.getUid() + ",");
        }
        sms2PrivService.smsSenders(buffer2,sb.toString());
    }

    @Async
    public void addAffairs(final HstMeetingWithBLOBs hstMeetingWithBLOBs, HttpServletRequest request) {
        final String sqlType = (String) request.getSession().getAttribute("loginDateSouse");
        Cookie redisSessionId = CookiesUtil.getCookieByName(request,"redisSessionId");
        Users users = SessionUtils.getSessionInfo(request.getSession(),Users.class,new Users(),redisSessionId);

        String userName = users.getUserName();
        ContextHolder.setConsumerType("xoa" + sqlType);
        if (StringUtils.checkNull(hstMeetingWithBLOBs.getUserId())){//更新时
            users = usersMapper.getUserId(hstMeetingMapper.selectByPrimaryKey(hstMeetingWithBLOBs.getMeetingId()).getUserId());
        }else {
            users = usersMapper.getUserId(hstMeetingWithBLOBs.getUserId());
        }

        SmsBody smsBody = new SmsBody();
        smsBody.setFromId(users.getUserId());
        smsBody.setContent("请审批我的会议！主题：" + hstMeetingWithBLOBs.getSubject());
//                if(!StringUtils.checkNull(meetingWithBLOBs.getStartTime())){
//                    smsBody.setSendTime(DateFormat.getTime(meetingWithBLOBs.getStartTime()));
//                }
                smsBody.setSendTime(DateFormat.getTime(DateFormat.getCurrentTime()));
                SysCode sysCode = new SysCode();
                sysCode.setCodeName("视频会议");
                sysCode.setParentNo("SMS_REMIND");
                if (sysCodeMapper.getCodeNoByNameAndParentNo(sysCode) != null) {
                    smsBody.setSmsType(sysCodeMapper.getCodeNoByNameAndParentNo(sysCode).getCodeNo());
                }
                if (!StringUtils.checkNull(hstMeetingWithBLOBs.getAttachmentId()) && !StringUtils.checkNull(hstMeetingWithBLOBs.getAttachmentName())) {
                    smsBody.setIsAttach("1");
                }
                //toUserId
                /*String toUserId="";
                if(hstMeetingWithBLOBs.getManagerId()!=null){
                    Users temp=usersMapper.getUserId(hstMeetingWithBLOBs.getManagerId().split(",")[0]);
                    if(temp!=null){
                        toUserId=temp.getUserId();
                    }
                }*/
                String toUserId="";
                if (!StringUtils.checkNull(hstMeetingWithBLOBs.getManagerId())) {
                    String[] split = hstMeetingWithBLOBs.getManagerId().split(",");
                    List<Users> getManagerId = usersMapper.getUsersByUserIds(split);
                    StringBuffer sb = new StringBuffer();
                    for (Users u : getManagerId) {
                        sb.append(u.getUserId() + ",");
                    }
                    if(sb!=null){
                        toUserId=sb.toString();
                    }
                }
                smsBody.setRemindUrl("/HSTmeeting/approval?meetingId="+hstMeetingWithBLOBs.getMeetingId());
                String title = userName + "：请审批我的视频会议！";
                String context = "主题:" + hstMeetingWithBLOBs.getSubject();
                smsService.saveSms(smsBody, toUserId, "1", "1", title, context, sqlType);
            /*}
        });*/
    }

    public HstRoomMapper getHstRoomMapper() {
        return hstRoomMapper;
    }

    public void setHstRoomMapper(HstRoomMapper hstRoomMapper) {
        this.hstRoomMapper = hstRoomMapper;
    }

    public HstMeetingMapper getHstMeetingMapper() {
        return hstMeetingMapper;
    }

    public void setHstMeetingMapper(HstMeetingMapper hstMeetingMapper) {
        this.hstMeetingMapper = hstMeetingMapper;
    }



    public ToJson<HstMeetingWithBLOBs> HstMeetingWithBLOBs(HttpServletRequest request, HstMeetingWithBLOBs hstMeetingWithBLOBs, Integer page, Integer limit, boolean useFlag, String date) {
        ToJson<HstMeetingWithBLOBs> json = new ToJson<HstMeetingWithBLOBs>(1, "error");
        try {
            Cookie redisSessionId = CookiesUtil.getCookieByName(request, "redisSessionId");
            Users user = SessionUtils.getSessionInfo(request.getSession(), Users.class, new Users(), redisSessionId);

            //分页
            //Integer type=hstMeetingWithBLOBs.getStatus();
            PageParams pageParams = new PageParams();
            pageParams.setPage(page);
            pageParams.setPageSize(limit);
            pageParams.setUseFlag(useFlag);
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("page", pageParams);
            String userId = user.getUserId();//查询当前登录人的会议申请
            map.put("userId",userId);
            map.put("hstMeetingWithBLOBs",hstMeetingWithBLOBs);
            Map<String, Object> map2 = new HashMap<String, Object>();
            map2.put("userId",userId);
            map2.put("hstMeetingWithBLOBs",hstMeetingWithBLOBs);

            // 修改会议状态
            //meetingStatus2();
            int count=0;
            List<HstMeetingWithBLOBs> meetingList = new ArrayList<HstMeetingWithBLOBs>();
            if ("2".equals(hstMeetingWithBLOBs.getMeetStatus())){
                count = hstMeetingMapper.selectAllMeeting2Count(map2);
                meetingList = hstMeetingMapper.selectAllMeeting2(map);

            } else if(StringUtils.checkNull(hstMeetingWithBLOBs.getMeetStatus())){
                count = hstMeetingMapper.selectAlls(userId);//总数
                meetingList = hstMeetingMapper.selectAll(map);
            }
            else{
                meetingList = hstMeetingMapper.selectAllMeeting(map);
                count = hstMeetingMapper.selectAllMeetingCount(map2);//总数
            }
            for (HstMeetingWithBLOBs meeting:meetingList){
                if (!StringUtils.checkNull(meeting.getRoomId()+"")){
                    HstRoomWithBLOBs hstRoomWithBLOBs = hstRoomMapper.selectMeetRoomManager(meeting.getRoomId());

                     meeting.setHstRoomWithBLOBs(hstRoomWithBLOBs);

                    String[] split = meeting.getHstRoomWithBLOBs().getRoomManager().split(",");
                    List<Users> usersByUids = usersMapper.getUsersByUserIds(split);
                    StringBuffer sb = new StringBuffer();
                    for (Users u : usersByUids) {
                        sb.append(u.getUserName() + ",");
                    }
                    meeting.getHstRoomWithBLOBs().setRoomManagerName(sb.toString());
                }
                if (!StringUtils.checkNull(meeting.getUserId())) {
                    meeting.setUserIdName(usersMapper.getUsernameByUserId(meeting.getUserId()));
                }
                if (!StringUtils.checkNull(String.valueOf(meeting.getRoomId()))){
                    meeting.setRoomName(hstRoomMapper.selectByPrimaryKey(meeting.getRoomId()).getRoomName());
                }
                if (!StringUtils.checkNull(meeting.getUserIds())) {
                    String[] split = meeting.getUserIds().split(",");
                    List<Users> usersByUids = usersMapper.getUsersByUserIds(split);
                    StringBuffer sb = new StringBuffer();
                    for (Users u : usersByUids) {
                        sb.append(u.getUserName() + ",");
                    }
                    meeting.setUserIdsName(sb.toString());
                }
            }
            json.setTotleNum(count);
            json.setObj(meetingList);
            json.setFlag(0);
            json.setMsg("ok");

        } catch (Exception e) {
            e.printStackTrace();
        }
        return json;
    }

    public ToJson<HstMeetingWithBLOBs> selectMeetingId(HttpServletRequest request, HttpServletResponse response, Integer meetingId) {
        ToJson<HstMeetingWithBLOBs> json = new ToJson<HstMeetingWithBLOBs>(1, "error");
        try {
            Cookie redisSessionId = CookiesUtil.getCookieByName(request, "redisSessionId");
            Users user = SessionUtils.getSessionInfo(request.getSession(), Users.class, new Users(), redisSessionId);
            Map<String, Object> map = new HashMap<String, Object>();
            String userId = user.getUserId();//查询当前登录人的会议申请
            map.put("meetingId",meetingId);
            HstMeetingWithBLOBs meeting = hstMeetingMapper.selectByPrimaryKey(meetingId);

                if (!StringUtils.checkNull(meeting.getUserId())) {
                    meeting.setUserIdName(usersMapper.getUsernameByUserId(meeting.getUserId()));
                }
                if (!StringUtils.checkNull(String.valueOf(meeting.getRoomId()))){
                    meeting.setRoomName(hstRoomMapper.selectByPrimaryKey(meeting.getRoomId()).getRoomName());
                }
                if (!StringUtils.checkNull(meeting.getUserIds())) {
                    String[] split = meeting.getUserIds().split(",");
                    List<Users> usersByUids = usersMapper.getUsersByUserIds(split);
                    StringBuffer sb = new StringBuffer();
                    for (Users u : usersByUids) {
                        sb.append(u.getUserName() + ",");
                    }
                    meeting.setUserIdsName(sb.toString());
                }
            if (!StringUtils.checkNull(meeting.getManagerId())) {
                String[] split = meeting.getManagerId().split(",");
                List<Users> getManagerId = usersMapper.getUsersByUserIds(split);
                StringBuffer sb = new StringBuffer();
                for (Users u : getManagerId) {
                    sb.append(u.getUserName() + ",");
                }
                meeting.setManagerIdName(sb.toString());
            }
            HstRoomWithBLOBs hstRoomWithBLOBs = hstRoomMapper.selectMeetRoomManager(meeting.getRoomId());
            if (!StringUtils.checkNull(hstRoomWithBLOBs.getRoomManager())) {
                String[] split = hstRoomWithBLOBs.getRoomManager().split(",");
                List<Users> getManagerId = usersMapper.getUsersByUserIds(split);
                meeting.setRoomManagerNames(getManagerId);
            }
            List<Attachment> attachmentList = new ArrayList<Attachment>();
            attachmentList = GetAttachmentListUtil.returnAttachment(meeting.getAttachmentName(), meeting.getAttachmentId(),  "xoa" + (String) request.getSession().getAttribute("loginDateSouse"), GetAttachmentListUtil.MODULE_MEETING);
            meeting.setAttachmentList(attachmentList);
            //json.setObj(hstMeetingWithBLOBs);

            json.setObj1(meeting);
            json.setFlag(0);
            json.setMsg("ok");

        } catch (Exception e) {
            e.printStackTrace();
        }
        return json;
    }

    public ToJson<HstMeetingWithBLOBs> updateMeetingById(HstMeetingWithBLOBs hstMeetingWithBLOBs,HttpServletRequest request) {
        ToJson<HstMeetingWithBLOBs> json = new ToJson<HstMeetingWithBLOBs>(1, "error");
        final String sqlType = (String) request.getSession().getAttribute("loginDateSouse");
        Cookie redisSessionId = CookiesUtil.getCookieByName(request,"redisSessionId");
        Users users = SessionUtils.getSessionInfo(request.getSession(),Users.class,new Users(),redisSessionId);
        try {
            int i = hstMeetingMapper.updateByPrimaryKeySelective(hstMeetingWithBLOBs);
            if ("1".equals(hstMeetingWithBLOBs.getSmsRemind())){//1 发送事务提醒
                addAffairs(hstMeetingWithBLOBs,request);
            }
            if ("1".equals(hstMeetingWithBLOBs.getSmsRemind2())){//1 发送短信提醒
                addMessage(hstMeetingWithBLOBs,request,users.getUid());
            }
            json.setFlag(0);
            json.setMsg("ok");

        } catch (Exception e) {
            e.printStackTrace();
        }
        return json;
    }

    public ToJson<HstMeetingWithBLOBs> delMeetingById(Integer meetingId) {
        ToJson<HstMeetingWithBLOBs> json = new ToJson<HstMeetingWithBLOBs>(1, "error");
        try {
            int i = hstMeetingMapper.deleteByPrimaryKey(meetingId);
            json.setFlag(0);
            json.setMsg("ok");

        } catch (Exception e) {
            e.printStackTrace();
        }
        return json;
    }

    public ToJson<HstMeetingWithBLOBs> selectMeetStatus(HttpServletRequest request, HttpServletResponse response, Integer meetStatus,Integer page, Integer pageSize, boolean useFlag) {
        ToJson<HstMeetingWithBLOBs> json = new ToJson<HstMeetingWithBLOBs>(1, "error");
        Cookie redisSessionId = CookiesUtil.getCookieByName(request,"redisSessionId");
        Users user = SessionUtils.getSessionInfo(request.getSession(),Users.class,new Users(),redisSessionId);
        try {
            PageParams pageParams = new PageParams();
            pageParams.setPage(page);
            pageParams.setPageSize(pageSize);
            pageParams.setUseFlag(useFlag);
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("page", pageParams);
            String userId = user.getUserId();//查询当前登录人的会议申请
            map.put("meetStatus",meetStatus);
            map.put("userId",userId);//申请人
            List<HstMeetingWithBLOBs> meetingList = hstMeetingMapper.selectMeetStatus(map);
            for (HstMeetingWithBLOBs meeting:meetingList){
                if (!StringUtils.checkNull(meeting.getUserId())) {
                    meeting.setUserIdName(usersMapper.getUsernameByUserId(meeting.getUserId()));
                }
                if (!StringUtils.checkNull(String.valueOf(meeting.getRoomId()))){
                    meeting.setRoomName(hstRoomMapper.selectByPrimaryKey(meeting.getRoomId()).getRoomName());
                }
                if (!StringUtils.checkNull(meeting.getUserIds())) {
                    String[] split = meeting.getUserIds().split(",");
                    List<Users> usersByUids = usersMapper.getUsersByUserIds(split);
                    StringBuffer sb = new StringBuffer();
                    for (Users u : usersByUids) {
                        sb.append(u.getUserName() + ",");
                    }
                    meeting.setUserIdsName(sb.toString());
                }
                if (!StringUtils.checkNull(meeting.getManagerId())) {
                    String[] split = meeting.getManagerId().split(",");
                    List<Users> getManagerId = usersMapper.getUsersByUserIds(split);
                    StringBuffer sb = new StringBuffer();
                    for (Users u : getManagerId) {
                        sb.append(u.getUserName() + ",");
                    }
                    meeting.setManagerIdName(sb.toString());
                }
            }
            json.setObj(meetingList);
            json.setMsg("ok");
            json.setFlag(0);
        }catch(Exception e){
            json.setMsg(e.getMessage());
        }
        return json;
    }

    public ToJson<HstMeetingWithBLOBs> updateMeetingStatus(String meetStatus, Integer meetingId,HttpServletRequest request,String smsRemind,String smsRemind2) {
        ToJson<HstMeetingWithBLOBs> json = new ToJson<HstMeetingWithBLOBs>(1, "error");
        try {
            int i = hstMeetingMapper.updateMeetingStatus(meetStatus,meetingId);
            HstMeetingWithBLOBs hstMeetingWithBLOBs1 = hstMeetingMapper.selectByPrimaryKey(meetingId);
            if ("1".equals(smsRemind)){
                this.addHstAffairs2(hstMeetingWithBLOBs1,request);
            }
            if ("1".equals(smsRemind2)){//1 发送短信提醒
                this.addMessage1(hstMeetingWithBLOBs1,request,hstMeetingWithBLOBs1.getUserIds());
            }
            json.setFlag(0);
            json.setMsg("ok");

        } catch (Exception e) {
            e.printStackTrace();
        }
        return json;
    }

    public ToJson<HstMeetingWithBLOBs> selectMeetingMy(HttpServletRequest request, HstMeetingWithBLOBs hstMeetingWithBLOBs, Integer page, Integer limit, boolean useFlag, String date) {
        ToJson<HstMeetingWithBLOBs> json = new ToJson<HstMeetingWithBLOBs>(1, "error");
        try {
            Cookie redisSessionId = CookiesUtil.getCookieByName(request, "redisSessionId");
            Users user = SessionUtils.getSessionInfo(request.getSession(), Users.class, new Users(), redisSessionId);

            //分页
            //Integer type=hstMeetingWithBLOBs.getStatus();
            PageParams pageParams = new PageParams();
            pageParams.setPage(page);
            pageParams.setPageSize(limit);
            pageParams.setUseFlag(useFlag);
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("page", pageParams);
            String userId = user.getUserId();//查询当前登录人的会议申请
            map.put("userId",userId);
            List<HstMeetingWithBLOBs> meetingList = new ArrayList<HstMeetingWithBLOBs>();
            meetingList = hstMeetingMapper.selectMeetingMy(map);
            int count = hstMeetingMapper.selectMeetingMys(userId);//总数
            for (HstMeetingWithBLOBs meeting:meetingList){
                if (!StringUtils.checkNull(meeting.getUserId())) {
                    meeting.setUserIdName(usersMapper.getUsernameByUserId(meeting.getUserId()));
                }
                if (!StringUtils.checkNull(String.valueOf(meeting.getRoomId()))){
                    meeting.setRoomName(hstRoomMapper.selectByPrimaryKey(meeting.getRoomId()).getRoomName());
                }
                if (!StringUtils.checkNull(meeting.getUserIds())) {
                    String[] split = meeting.getUserIds().split(",");
                    List<Users> usersByUids = usersMapper.getUsersByUserIds(split);
                    StringBuffer sb = new StringBuffer();
                    for (Users u : usersByUids) {
                        sb.append(u.getUserName() + ",");
                    }
                    meeting.setUserIdsName(sb.toString());
                }
                if (!StringUtils.checkNull(meeting.getManagerId())) {
                    String[] split = meeting.getManagerId().split(",");
                    List<Users> getManagerId = usersMapper.getUsersByUserIds(split);
                    StringBuffer sb = new StringBuffer();
                    for (Users u : getManagerId) {
                        sb.append(u.getUserName() + ",");
                    }
                    meeting.setManagerIdName(sb.toString());
                }
            }
            json.setObj(meetingList);
            json.setTotleNum(count);
            json.setFlag(0);
            json.setMsg("ok");

        } catch (Exception e) {
            e.printStackTrace();
        }
        return json;
    }

    public ToJson<HstMeetingWithBLOBs> selectMeetStatusMy(HttpServletRequest request, HttpServletResponse response, Integer meetStatus, Integer page, Integer limit, boolean useFlag) {
        ToJson<HstMeetingWithBLOBs> json = new ToJson<HstMeetingWithBLOBs>(1, "error");
        Cookie redisSessionId = CookiesUtil.getCookieByName(request,"redisSessionId");
        Users user = SessionUtils.getSessionInfo(request.getSession(),Users.class,new Users(),redisSessionId);
        try {
            PageParams pageParams = new PageParams();
            pageParams.setPage(page);
            pageParams.setPageSize(limit);
            pageParams.setUseFlag(useFlag);
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("page", pageParams);
            String userId = user.getUserId();//查询当前登录人的会议申请
            map.put("meetStatus",meetStatus);
            map.put("userId",userId);//申请人
            map.put("userPriv",user.getUserPriv());//申请人为1  管理员也能审批
            List<HstMeetingWithBLOBs> meetingList = hstMeetingMapper.selectMeetStatusMy(map);
            int count = hstMeetingMapper.selectMeetStatusMyCount(meetStatus,userId);
            for (HstMeetingWithBLOBs meeting:meetingList){
                if (!StringUtils.checkNull(meeting.getRoomId()+"")){
                    HstRoomWithBLOBs hstRoomWithBLOBs = hstRoomMapper.selectMeetRoomManager(meeting.getRoomId());

                    meeting.setHstRoomWithBLOBs(hstRoomWithBLOBs);

                    String[] split = meeting.getHstRoomWithBLOBs().getRoomManager().split(",");
                    List<Users> usersByUids = usersMapper.getUsersByUserIds(split);
                    StringBuffer sb = new StringBuffer();
                    for (Users u : usersByUids) {
                        sb.append(u.getUserName() + ",");
                    }
                    meeting.getHstRoomWithBLOBs().setRoomManagerName(sb.toString());
                }
                if (!StringUtils.checkNull(meeting.getUserId())) {
                    meeting.setUserIdName(usersMapper.getUsernameByUserId(meeting.getUserId()));
                }
                if (!StringUtils.checkNull(String.valueOf(meeting.getRoomId()))){
                    meeting.setRoomName(hstRoomMapper.selectByPrimaryKey(meeting.getRoomId()).getRoomName());
                }
                if (!StringUtils.checkNull(meeting.getUserIds())) {
                    String[] split = meeting.getUserIds().split(",");
                    List<Users> usersByUids = usersMapper.getUsersByUserIds(split);
                    StringBuffer sb = new StringBuffer();
                    for (Users u : usersByUids) {
                        sb.append(u.getUserName() + ",");
                    }
                    meeting.setUserIdsName(sb.toString());
                }
                if (!StringUtils.checkNull(meeting.getManagerId())) {
                    String[] split = meeting.getManagerId().split(",");
                    List<Users> getManagerId = usersMapper.getUsersByUserIds(split);
                    StringBuffer sb = new StringBuffer();
                    for (Users u : getManagerId) {
                        sb.append(u.getUserName() + ",");
                    }
                    meeting.setManagerIdName(sb.toString());
                }
            }
            json.setTotleNum(pageParams.getTotal());
            json.setObj(meetingList);
            json.setMsg("ok");
            json.setFlag(0);
        }catch(Exception e){
            json.setMsg(e.getMessage());
        }
        return json;
    }

    /**
     * 审批发送事务提醒
     * @param
     * @param request
     */
    @Async
    public void addHstAffairs1(final HstMeetingWithBLOBs hstMeetingWithBLOBs, HttpServletRequest request) {
        final String sqlType = (String) request.getSession().getAttribute("loginDateSouse");
        Cookie redisSessionId = CookiesUtil.getCookieByName(request,"redisSessionId");
        Users users = SessionUtils.getSessionInfo(request.getSession(),Users.class,new Users(),redisSessionId);

        String userName = users.getUserName();
        ContextHolder.setConsumerType("xoa" + sqlType);
        if (StringUtils.checkNull(hstMeetingWithBLOBs.getUserId())){//更新时
            users = usersMapper.getUserId(hstMeetingMapper.selectByPrimaryKey(hstMeetingWithBLOBs.getMeetingId()).getUserId());
        }else {
            users = usersMapper.getUserId(hstMeetingWithBLOBs.getUserId());
        }

        SmsBody smsBody = new SmsBody();
        smsBody.setFromId(users.getUserId());
        smsBody.setContent("请审批我的会议！主题：" + hstMeetingWithBLOBs.getSubject());
//                if(!StringUtils.checkNull(meetingWithBLOBs.getStartTime())){
//                    smsBody.setSendTime(DateFormat.getTime(meetingWithBLOBs.getStartTime()));
//                }
        smsBody.setSendTime(DateFormat.getTime(DateFormat.getCurrentTime()));
        SysCode sysCode = new SysCode();
        sysCode.setCodeName("视频会议");
        sysCode.setParentNo("SMS_REMIND");
        if (sysCodeMapper.getCodeNoByNameAndParentNo(sysCode) != null) {
            smsBody.setSmsType(sysCodeMapper.getCodeNoByNameAndParentNo(sysCode).getCodeNo());
        }
        if (!StringUtils.checkNull(hstMeetingWithBLOBs.getAttachmentId()) && !StringUtils.checkNull(hstMeetingWithBLOBs.getAttachmentName())) {
            smsBody.setIsAttach("1");
        }
        //toUserId
                /*String toUserId="";
                if(hstMeetingWithBLOBs.getManagerId()!=null){
                    Users temp=usersMapper.getUserId(hstMeetingWithBLOBs.getManagerId().split(",")[0]);
                    if(temp!=null){
                        toUserId=temp.getUserId();
                    }
                }*/
        String toUserId="";
        if (!StringUtils.checkNull(hstMeetingWithBLOBs.getManagerId())) {//给会议室所有管理员都发事务提醒
            String[] split = hstRoomMapper.selectByPrimaryKey(hstMeetingWithBLOBs.getRoomId()).getRoomManager().split(",");
            List<Users> getManagerId = usersMapper.getUsersByUserIds(split);
            StringBuffer sb = new StringBuffer();
            for (Users u : getManagerId) {
                sb.append(u.getUserId() + ",");
            }
            if(sb!=null){
                toUserId=sb.toString();
            }
        }
        smsBody.setRemindUrl("/HSTmeeting/approval?meetingId="+hstMeetingWithBLOBs.getMeetingId());
        String title = userName + "：请审批我的视频会议！";
        String context = "主题:" + hstMeetingWithBLOBs.getSubject();
        smsService.saveSms(smsBody, toUserId, "1", "1", title, context, sqlType);
            /*}
        });*/
    }
    @Async
    public void addHstAffairs2(final HstMeetingWithBLOBs hstMeetingWithBLOBs, HttpServletRequest request) {//给参会人员发送事务提醒
        final String sqlType = (String) request.getSession().getAttribute("loginDateSouse");
        Cookie redisSessionId = CookiesUtil.getCookieByName(request,"redisSessionId");
        Users users = SessionUtils.getSessionInfo(request.getSession(),Users.class,new Users(),redisSessionId);

        String userName = users.getUserName();
        ContextHolder.setConsumerType("xoa" + sqlType);
        if (StringUtils.checkNull(hstMeetingWithBLOBs.getUserId())){//更新时
            users = usersMapper.getUserId(hstMeetingMapper.selectByPrimaryKey(hstMeetingWithBLOBs.getMeetingId()).getUserId());
        }else {
            users = usersMapper.getUserId(hstMeetingWithBLOBs.getUserId());
        }

        SmsBody smsBody = new SmsBody();
        smsBody.setFromId(users.getUserId());
        smsBody.setContent("请参加会议，会议名称：" + hstMeetingWithBLOBs.getMeetName());
//                if(!StringUtils.checkNull(meetingWithBLOBs.getStartTime())){
//                    smsBody.setSendTime(DateFormat.getTime(meetingWithBLOBs.getStartTime()));
//                }
        smsBody.setSendTime(DateFormat.getTime(DateFormat.getCurrentTime()));
        SysCode sysCode = new SysCode();
        sysCode.setCodeName("视频会议");
        sysCode.setParentNo("SMS_REMIND");
        if (sysCodeMapper.getCodeNoByNameAndParentNo(sysCode) != null) {
            smsBody.setSmsType(sysCodeMapper.getCodeNoByNameAndParentNo(sysCode).getCodeNo());
        }
        if (!StringUtils.checkNull(hstMeetingWithBLOBs.getAttachmentId()) && !StringUtils.checkNull(hstMeetingWithBLOBs.getAttachmentName())) {
            smsBody.setIsAttach("1");
        }
        //toUserId
                /*String toUserId="";
                if(hstMeetingWithBLOBs.getManagerId()!=null){
                    Users temp=usersMapper.getUserId(hstMeetingWithBLOBs.getManagerId().split(",")[0]);
                    if(temp!=null){
                        toUserId=temp.getUserId();
                    }
                }*/
        String toUserId="";
        if (!StringUtils.checkNull(hstMeetingWithBLOBs.getUserIds())) {
            String[] split = hstMeetingWithBLOBs.getUserIds().split(",");
            List<Users> getManagerId = usersMapper.getUsersByUserIds(split);
            StringBuffer sb = new StringBuffer();
            for (Users u : getManagerId) {
                sb.append(u.getUserId()+ ",");
            }
            if(sb!=null){
                toUserId=sb.toString();
            }
        }
        smsBody.setRemindUrl("/hstMeetingRoom/myHstMeeting?meetingId="+hstMeetingWithBLOBs.getMeetingId());
        String title = userName + "：请按时参加视频会议！";
        String context = "主题:" + hstMeetingWithBLOBs.getSubject();
        smsService.saveSms(smsBody, toUserId, "1", "1", title, context, sqlType);
            /*}
        });*/
    }
    public ToJson<HstMeetingWithBLOBs> getApp(Map<String, Object> maps, Integer page, Integer pageSize, Boolean useFlag, String userId, String sqlType){
        ToJson<HstMeetingWithBLOBs> json = new ToJson<HstMeetingWithBLOBs>(1, "error");
        PageParams pageParams = new PageParams();
        pageParams.setPage(page);
        pageParams.setPageSize(pageSize);
        pageParams.setUseFlag(useFlag);
        meetingStatus();
        maps.put("page", pageParams);
        maps.put("userId",userId);
        List<HstMeetingWithBLOBs> app = hstMeetingMapper.getApp(maps);
        json.setObj(app);
        return json;
    }

    public void meetingStatus(){
        List<HstMeetingWithBLOBs> hstMeetingWithBLOBs =hstMeetingMapper.selectAllApp();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = new Date();
        long currentTime=date.getTime();
        for (HstMeetingWithBLOBs meeting:hstMeetingWithBLOBs){
            long startTime=0;
            long endTime=0;
            if(null!=meeting.getStartTime()){
                startTime= meeting.getStartTime().getTime();
                //startTime=Long.valueOf(DateFormat.getTime(sdf.format(meeting.getStartTime())));
            }
            if(null!=meeting.getEndTime()){
                endTime= meeting.getEndTime().getTime();
                //endTime=Long.valueOf(DateFormat.getTime(sdf.format(meeting.getEndTime())));

            }

            if(meeting.getMeetStatus()!=null){
                switch(Integer.parseInt(meeting.getMeetStatus())){
                    case 1:
                        meeting.setMeetStatusString("待审批");
                        break;
                    case 2:
                        if(startTime<=currentTime && currentTime<endTime){
                            meeting.setMeetStatusString("进行中");
                            meeting.setMeetStatus("3");
                        }else if(startTime<=currentTime && currentTime>=endTime){
                            meeting.setMeetStatusString("已结束");
                            meeting.setMeetStatus("5");
                        }else{
                            meeting.setMeetStatusString("已审批");
                            meeting.setMeetStatus("2");
                        }
                        //对时间进行了判断，修改数据库，并更改返回值
                        /*int i = hstMeetingMapper.updHstMeetStatusById(meeting);
                        try {
                            if (i>0){
                                BudgetLog log = new BudgetLog();
                                log.setBudgetId(meeting.getMeetingId());
                                log.setUserId("user.getUserId()");
                                log.setTime(sdf.format(new Date()));// 现在时间
                                try {
                                    log.setIp(sdf.format(meeting.getStartTime()));
                                }catch (Exception e){

                                }
                                log.setType(String.valueOf(meeting.getMeetStatus()));
                                log.setRemark("ip==开始时间，，input==结束时间");
                                log.setBudgetItemName("767");
                                try {
                                    log.setBudgetInputTime(meeting.getEndTime());
                                }catch (Exception e){

                                }
                                budgetLogMapper.insertSelective(log);
                            }
                        }catch (Exception e){

                        }*/

                        break;
                    case 3:
                        if(startTime<=currentTime && currentTime>=endTime){
                            meeting.setMeetStatusString("已结束");
                            meeting.setMeetStatus("5");
                        }else {
                            meeting.setMeetStatusString("进行中");
                            meeting.setMeetStatus("3");
                        }
                        /*int i1 = hstMeetingMapper.updHstMeetStatusById(meeting);
                        try {
                            if (i1>0){
                                BudgetLog log = new BudgetLog();
                                log.setBudgetId(meeting.getMeetingId());
                                log.setUserId("user.getUserId()");
                                log.setTime(sdf.format(new Date()));// 现在时间
                                try {
                                    log.setIp(sdf.format(meeting.getStartTime()));
                                }catch (Exception e){

                                }
                                log.setType(String.valueOf(meeting.getMeetStatus()));
                                log.setRemark("ip==开始时间，，input==结束时间");
                                log.setBudgetItemName("797");
                                try {
                                    log.setBudgetInputTime(meeting.getEndTime());
                                }catch (Exception e){

                                }
                                budgetLogMapper.insertSelective(log);
                            }
                        }catch (Exception e){

                        }*/

                        break;
                    case 4:
                        meeting.setMeetStatusString("未批准");
                        break;
                    case 5:
                        meeting.setMeetStatusString("已结束");
                        break;
                }
            }
        }
    }

    public void meetingStatus2(){
        List<HstMeetingWithBLOBs> hstMeetingWithBLOBs =hstMeetingMapper.selectAllApp();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = new Date();
        long currentTime=date.getTime();
        for (HstMeetingWithBLOBs meeting:hstMeetingWithBLOBs){
            long startTime=0;
            long endTime=0;
            if(null!=meeting.getStartTime()){
                startTime= meeting.getStartTime().getTime();
                //startTime=Long.valueOf(DateFormat.getTime(sdf.format(meeting.getStartTime())));
            }
            if(null!=meeting.getEndTime()){
                endTime= meeting.getEndTime().getTime();
                //endTime=Long.valueOf(DateFormat.getTime(sdf.format(meeting.getEndTime())));

            }

            if(meeting.getMeetStatus()!=null){
                switch(Integer.parseInt(meeting.getMeetStatus())){
                    case 1:
                        meeting.setMeetStatusString("待审批");
                        break;
                    case 2:
                        if(startTime<=currentTime && currentTime<endTime){
                            meeting.setMeetStatusString("进行中");
                            meeting.setMeetStatus("3");
                        }else if(startTime<=currentTime && currentTime>=endTime){
                            meeting.setMeetStatusString("已结束");
                            meeting.setMeetStatus("5");
                        }else{
                            meeting.setMeetStatusString("已审批");
                            meeting.setMeetStatus("2");
                        }
                        //对时间进行了判断，修改数据库，并更改返回值
                        int i = hstMeetingMapper.updHstMeetStatusById(meeting);
                        /*try {
                            if (i>0&&!meeting.getMeetStatus().equals("2")){
                                BudgetLog log = new BudgetLog();
                                log.setBudgetId(meeting.getMeetingId());
                                log.setUserId(String.valueOf(currentTime));
                                log.setTime(sdf.format(date));// 现在时间
                                try {
                                    log.setIp(meeting.getStartTime()+"////"+startTime);
                                }catch (Exception e){

                                }
                                log.setType(String.valueOf(meeting.getMeetStatus()));
                                log.setRemark("ip==开始时间，，budgetItemName==结束时间"+873);
                                log.setBudgetItemName(meeting.getEndTime()+"///"+endTime);
                                try {
                                    //log.setBudgetInputTime();
                                }catch (Exception e){

                                }
                                budgetLogMapper.insertSelective(log);
                            }
                        }catch (Exception e){

                        }*/
                        break;
                    case 3:
                        /*meeting.setMeetStatusString("进行中");
                        meeting.setMeetStatus("3");*/
                        if(startTime<=currentTime && currentTime>=endTime){
                            meeting.setMeetStatusString("已结束");
                            meeting.setMeetStatus("5");
                        }else {
                            meeting.setMeetStatusString("进行中");
                            meeting.setMeetStatus("3");
                        }
                        int i1 = hstMeetingMapper.updHstMeetStatusById(meeting);
                        /*try {
                            if (i1>0&&!meeting.getMeetStatus().equals("3")){
                                BudgetLog log = new BudgetLog();
                                log.setBudgetId(meeting.getMeetingId());
                                log.setUserId(String.valueOf(currentTime));
                                log.setTime(sdf.format(new Date()));// 现在时间
                                try {
                                    log.setIp(sdf.format(meeting.getStartTime())+"////"+startTime);
                                }catch (Exception e){

                                }
                                log.setType(String.valueOf(meeting.getMeetStatus()));
                                log.setRemark("ip==开始时间，，input==结束时间"+"///"+909);
                                log.setBudgetItemName(sdf.format(meeting.getEndTime())+"////"+endTime);
                                try {
                                    //log.setBudgetInputTime(meeting.getEndTime());
                                }catch (Exception e){

                                }
                                budgetLogMapper.insertSelective(log);
                            }
                        }catch (Exception e){

                        }*/

                        break;
                    case 4:
                        meeting.setMeetStatusString("未批准");
                        break;
                    case 5:
                        meeting.setMeetStatusString("已结束");
                        break;
                }
            }
        }
    }

    public Sms2PrivService getSms2PrivService() {
        return sms2PrivService;
    }

    public void setSms2PrivService(Sms2PrivService sms2PrivService) {
        this.sms2PrivService = sms2PrivService;
    }

    public ToJson<HstMeetingWithBLOBs> hstMeetingView(HttpServletRequest request, HstMeetingWithBLOBs hstMeetingWithBLOBs, String date) {
        ToJson<HstMeetingWithBLOBs> json = new ToJson<HstMeetingWithBLOBs>(1, "error");
        //meetingStatus();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        if(!StringUtils.checkNull(date)){
            try {
                hstMeetingWithBLOBs.setStartTime(sdf.parse(DateFormat.getMonthStart(Integer.parseInt(date.substring(0,4)),Integer.parseInt(date.substring(5,7)))));
            } catch (ParseException e) {
                e.printStackTrace();
            }
            try {
                hstMeetingWithBLOBs.setEndTime(sdf.parse(DateFormat.getMonthEnd(Integer.parseInt(date.substring(0,4)),Integer.parseInt(date.substring(5,7)))));
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }
        List<HstMeetingWithBLOBs> app = hstMeetingMapper.hstMeetingView(hstMeetingWithBLOBs);
        json.setObj(app);
        json.setFlag(0);
        json.setMsg("ok");
        return json;
    }
}
